//
//  JSFormViewController.swift
//  fho
//
//  Created by 郭颢源 on 2021/3/20.
//

import UIKit


class JSFormViewController: BaseFormsController,UITableViewDelegate,UITableViewDataSource {

//    var isEdit = false//判断tableview是否是在编辑状态
//    var requestDict : NSMutableDictionary = {
//        var dict = NSMutableDictionary()
//        return dict
//        
//    }()
//    var uploadDict : NSMutableDictionary = {
//        var dict = NSMutableDictionary()
//        return dict
//    }()
//    var haveHeader : Bool = true
//    fileprivate lazy var datas:NSMutableArray = {
//        var array = NSMutableArray()
//        //        for i in 1...22{
//        //            array.add(NSNumber(value: i).stringValue)
//        //        }
//        return array
//        
//    }()
//    let  sectionHeaderHeight:CGFloat = 60
//    let  sectionFooterHeight:CGFloat = 40
//    lazy var tableView:UITableView = {
//        var table = UITableView(frame: .zero, style: .plain)
//        table.delegate = self
//        table.dataSource = self
//        table.showsVerticalScrollIndicator = false//垂直滚动指示器
//        table.showsHorizontalScrollIndicator = false//水平滚动指示器
//        //        table.bounces = false//弹簧效果
//        //        table.separatorStyle = .none//分割线
//        table.estimatedRowHeight = 0//预设行高
//        table.estimatedSectionFooterHeight = 0//预设分区头高度
//        table.estimatedSectionHeaderHeight = 0
//        table.backgroundColor = UIColor.white
//        table.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: -40, right: 0)
//        if #available(iOS 11.0, *) {
//            table.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.always
//        }
//        return table
//        
//    }()
    
    var showAll:Bool = true
    
    
    typealias RequestBlock = (_ name:String)->Void;
    var block : RequestBlock?;
    
    
   lazy var goods = [[String:Any]]()
    
    lazy var iconBtn:UIButton = {
        var _iconBtn = UIButton()
        _iconBtn.titleLabel!.font = UIFont.systemFont(ofSize: 16)
        _iconBtn.contentHorizontalAlignment = .center
        _iconBtn.setTitleColor(.white, for: .normal)
        _iconBtn.setTitle("确定", for: .normal)
        _iconBtn.backgroundColor = .systemOrange
        _iconBtn.sg_addCorner(radius: 20)
        
        _iconBtn.addTarget(self, action: #selector(subParams(_:)), for: .touchUpInside)
        return _iconBtn
    }()
    
    @objc func subParams(_ sender:UIButton) {
        sender.sg_timeInterval(time: 0.5)

        print(self.uploadDict)
        if goods.count <= 0 {
            JSShowMessage.showTipMsg("请添加货物", time: 1)
            var rect = tableView.rect(forSection: 2)
            rect.origin.y = 150
            tableView.scrollRectToVisible(rect, animated: true)
            
            return
        }
        
        
        var goodsname: String = ""
        var goodsnum: String = ""
        var packway: String = ""
        var weight: String = ""
        var volume: String = ""
        goods.forEach { (dict) in
            let dic = dict
            /**
             goodsname    是    string    物品 默认值 无/无/无
             goodsnum    是    string    物品数量 默认值 0/0/0
             packway    是    string    打包方式 默认值 无/无/无
             weight    是    string    物品重量 默认值 0/0/0
             volume    是    string    物品体积 默认值 0/0/0
             */
            let goodsnameValue = dic["goodsname"] as! String
            let goodsnumValue = dic["goodsnum"]  as! String
            let packwayTypeValue = dic["packwayType"]  as! String
            let volumeValue = dic["volume"]  as! String
            let weightValue = dic["weight"]  as! String
            
            goodsname += "/\(goodsnameValue)"
            goodsnum += "/\(goodsnumValue)"
            packway += "/\(packwayTypeValue)"
            weight += "/\(weightValue)"
            volume += "/\(volumeValue)"
        }
        self.uploadDict["goodsname"] = goodsname
        self.uploadDict["goodsnum"] = goodsnum
        self.uploadDict["packway"] = packway
        self.uploadDict["weight"] = weight
        self.uploadDict["volume"] = volume
        print("提交")
        print(self.uploadDict)

        
        if let section = self.datas.firstIndex(where: {!$0.content.filter({$0.text.isEmpty}).isEmpty}) {
            let row = self.datas[section].content.firstIndex(where: {$0.text.isEmpty})
            let indexPath = IndexPath(row: row!, section: section)
            tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
            DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
                let cell : JSBaseViewCell = self.tableView.cellForRow(at: indexPath) as! JSBaseViewCell
                UIView.animate(withDuration: 0.2) {
                    cell.backgroundColor = .systemRed
                } completion: { (make:Bool) in
                    cell.backgroundColor = .white
                }
            }
        }
        
//        // 停止类型1、停止类型2
//          BOOL scrollToScrollStop = !scrollView.tracking && !scrollView.dragging && !scrollView.decelerating;
//          if (scrollToScrollStop) {
//              [self scrollViewDidEndScroll];
//          }
        //更新保存
        let tempObj = NSKUserInfo.shared
        tempObj.read()
        self.uploadDict["token"] = tempObj.loginUser.token
        self.requestObj.requestTarget(.createOrder(params: self.uploadDict)) { (result) in
            print(result)
        } failure: { (code, msg) in
            print(code,msg)
        }
        
        


    }
    // 验证货物信息是否完整
    /// - Returns: 验证信息
    func validateValue() -> String{
        /**
         goodsname = 2323;
         goodsnum = "1.0";
         packway = 1;
         unit = "\U4ef6";
         unitPrice = 33333;
         volume = "4.0";
         weight = "4.0";
         */
        
        let goodsname = self.uploadDict.object(forKey: "goodsname") as? String
        let goodsnum = self.uploadDict.object(forKey: "goodsnum") as? String
        let packway = self.uploadDict.object(forKey: "packway") as? String
        let unit = self.uploadDict.object(forKey: "unit") as? String
        let unitPrice = self.uploadDict.object(forKey: "unitPrice") as? String
        let volume = self.uploadDict.object(forKey: "volume") as? String
        let weight = self.uploadDict.object(forKey: "weight") as? String
        guard goodsname != nil && goodsname!.count>0 else {            return "请输入货物名称"        }
        guard packway != nil && packway!.count>0 else {            return "请选择货物包装"        }
        guard unit != nil && unit!.count>0 else {            return "请选择计价单位"        }
        guard unitPrice != nil && unitPrice!.count>0 else {            return "请输入单价"        }
        
        guard goodsnum != nil && goodsnum!.count>0 else {            return "请输入货物数量"        }
        guard weight != nil && weight!.count>0 else {            return "请输入货物重量"        }
        guard volume != nil && volume!.count>0 else {            return "请输入货物体积"        }
        
        return ""
    }
    func checkHaveEmptyField(block:RequestBlock) {
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("will")
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.edgesForExtendedLayout = .init()
        
        let subItem:UIBarButtonItem = UIBarButtonItem(title: "确定", titleColor: .systemBlue, titleFont: UIFont.systemFont(ofSize: 16), titleEdgeInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0), target: self, action: #selector(subParams(_:)))
        self.navigationItem.rightBarButtonItem = subItem
        
        
        checkHaveEmptyField { (String) in
        
        }
        self.tableView.delegate = self
        self.tableView.dataSource = self
        view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20))
        }
        
        self.tableView.reloadData()
        
        // Do any additional setup after loading the view.
        
        let tableFooterView = UIView()
        tableFooterView.frame = CGRect(x: 0, y: 0, width: 0, height: 100)
        
        tableView.tableFooterView = tableFooterView
        
        tableFooterView.addSubview(iconBtn)
        iconBtn.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(tableFooterView.snp.centerX).offset(30)
            make.width.equalTo(80)
            make.height.equalTo(40)
        }
    }
    // MARK: - UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.datas.count
    }

    //返回cell的行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let headerModel = self.datas[section] as? JSFormHeaderModel
        if headerModel!.isFolding {
            return 0
        }else
        {
            return headerModel!.content.count
        }

    }
    //返回cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 2 {
            let Identifier:String = "JSGoodsFormsCell"
            var cell = tableView.dequeueReusableCell(withIdentifier: Identifier) as? JSBaseViewCell

            if cell == nil {
                cell = JSGoodsFormsCell(style: .default, reuseIdentifier: Identifier)
            }

            let headerModel = self.datas[indexPath.section] as? JSFormHeaderModel
            let model:JSFormModel = headerModel!.content[indexPath.row]
            cell!.initWith(Model: model, VC: self)
            return cell!
        }
        
        
        let model:JSFormModel = getCurrentFormModel(indexPath)
        let cell = tableView.dequeueReusableCell(withIdentifier: model.cellID as String, for: indexPath) as! JSBaseViewCell
        cell.initWith(Model: model, VC: self)
        
        return cell
    }
    //
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        let model:JSFormModel = getCurrentFormModel(indexPath);
        return model.height
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        print(indexPath)
        let cell : JSBaseViewCell = tableView.cellForRow(at: indexPath) as! JSBaseViewCell
        
        //        JSBaseViewCell  *cell = [tableView cellForRowAtIndexPath:indexPath];
        let model = getCurrentFormModel(indexPath)
        if (model.showInfo) {
            return;
        }
        self.view.endEditing(true)
        cell.doSomething()

    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section==2 {
            var header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "UITableViewHeaderFooterView")
            if header == nil {
                header = UITableViewHeaderFooterView(reuseIdentifier: "UITableViewHeaderFooterView")
            }
            header!.contentView.backgroundColor = .white
            return nil
            return header
        }
        
        var headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "FXFormHeaderViewID") as? JSFormHeaderView
        if headerView == nil {
            headerView = JSFormHeaderView(reuseIdentifier: "FXFormHeaderViewID")
        }
        
        let headerModel = self.datas[section] as? JSFormHeaderModel
        headerView?.model = (headerModel?.header)!
        headerView?.block = { str in
            //展开
            headerModel!.isFolding = !headerModel!.isFolding
            
            let set:IndexSet = IndexSet(integer: section)
            tableView.reloadSections(set as IndexSet, with: .fade)
        }
        
        headerView?.editBtn.isSelected = headerModel!.isFolding
        
        let name = headerModel?.content.first?.text
        let tel = headerModel?.content[1].text
        let content = name! + "  " + tel!
        let nameAttribute = [NSAttributedString.Key.foregroundColor: UIColor.black,
                           NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)] as [NSAttributedString.Key : Any]
        let telAttribute = [NSAttributedString.Key.foregroundColor: UIColor.lightGray,
                           NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)] as [NSAttributedString.Key : Any]
        let attString = NSMutableAttributedString(string: content)
        attString.addAttributes(nameAttribute, range: NSRange.init(location: 0, length: name!.count))
        attString.addAttributes(telAttribute, range: NSRange.init(location: content.count-tel!.count, length: tel!.count))
        

        switch section {
        case ...2:
            headerView?.content.attributedText = headerModel!.isFolding ? attString:nil
        default:
            headerView?.content.attributedText = nil
        }

        return headerView
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
       
        if section==2 {
            var footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: JSADDFooterViewID) as? JSADDFooterView
            if footer == nil {
                footer = JSADDFooterView(reuseIdentifier: JSADDFooterViewID)
            }
            
            footer?.block = {str in
                let headerModel = self.datas[section] as? JSFormHeaderModel
                
                if headerModel!.content.count>=3 {
                    JSShowMessage.showTipMsg("最多添加3种货物", time: 1)
                    return
                }
                let goodsForms = JSGoodsFormsController()
                self.navigationController?.pushViewController(goodsForms, animated: true)
                goodsForms.block = { [self] arr in
                    goods.append(contentsOf: arr)
                    arr.forEach { (dict) in
                        let dic = dict
                        
                        let goodsname = dic["goodsname"] as! String
                        let goodsnum = dic["goodsnum"]  as! String
                        let packwayType = dic["packwayType"]  as! String
                        let unit = dic["unit"]  as! String
                        let unitPrice = dic["unitPrice"]  as! String
                        let volume = dic["volume"]  as! String
                        let weight = dic["weight"]  as! String
                        
                        let model = JSFormModel()
                        model.icon = "icon_name"
                        model.name = goodsname
                        model.text = "\(packwayType)/\(goodsnum)件/\(weight)公斤/\(volume)方/ \(unitPrice)(元/\(unit))"
                        let headerModel = self.datas[section] as? JSFormHeaderModel
                        headerModel!.content.append(model)
                    }
                    
                    let index:IndexSet = IndexSet(integer: section)
                    tableView.reloadSections(index, with: .automatic)
                }
            }
            return footer
        }
                var footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "UITableViewHeaderFooterView")
                if footerView == nil {
                    footerView = UITableViewHeaderFooterView(reuseIdentifier: "UITableViewHeaderFooterView")
                }
        footerView?.contentView.backgroundColor = .systemRed
            return footerView
//        var footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: JSFormFooterViewID) as? JSFormFooterView
//        if footerView == nil {
//            footerView = JSFormFooterView(reuseIdentifier: JSFormFooterViewID)
//        }
//
//        let headerModel = self.datas[section] as? JSFormHeaderModel
////        footerView?.model = (headerModel?.header)!
//        let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(headViewClick))
//        footerView?.isUserInteractionEnabled = true
//        footerView?.addGestureRecognizer(tap)
//        footerView?.block = { str in
//            //折叠
//            headerModel!.isFolding = true
//
//            let set:IndexSet = IndexSet(integer: section)
//            tableView.reloadSections(set as IndexSet, with: .fade)
//        }
//        return (headerModel!.isFolding ? nil:footerView)
    }

    @objc func headViewClick() -> Void {
        if showAll {
            showAll = false
            
        }else{
            showAll = true
            
        }
        let set:IndexSet = IndexSet.init(integer: 0)
        tableView.reloadSections(set as IndexSet, with: .fade)
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section==2 {
            return 20
        }
        return self.haveHeader ? sectionHeaderHeight : CGFloat.leastNormalMagnitude
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section==2 {
            return sectionFooterHeight
        }
        return 0.01
        
        let headerModel = self.datas[section] as? JSFormHeaderModel
//        return headerModel!.isFolding ?CGFloat.leastNormalMagnitude: sectionFooterHeight
    }

//    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//
//            let  offsetY:CGFloat = scrollView.contentOffset.y
//
//        if (offsetY >= 0 && offsetY <= sectionHeaderHeight)
//           {
//            scrollView.contentInset = UIEdgeInsets(top: -0, left: 0, bottom: -sectionFooterHeight, right: 0);
//           }else if (offsetY >= sectionHeaderHeight && offsetY <= scrollView.contentSize.height - scrollView.frame.size.height - sectionFooterHeight)
//           {
//            scrollView.contentInset = UIEdgeInsets(top: -0, left: 0, bottom: -sectionFooterHeight, right: 0);
//           }else if (offsetY >= scrollView.contentSize.height - scrollView.frame.size.height - sectionFooterHeight && offsetY <= scrollView.contentSize.height - scrollView.frame.size.height)
//           {
//            scrollView.contentInset = UIEdgeInsets(top: -0, left: 0, bottom: 0, right: 0);
//           }
//
//    }
    
//    var rect:CGRect?
    
//    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        let  offsetY:CGFloat = scrollView.contentOffset.y
//        let cells = tableView.visibleCells
//        let cell = cells.first as! JSBaseViewCell
//        if cell.model.text.isEmpty {
//            rect = cell.convert(cell.bounds, to: self.view)
//
//        }
//        print(cells.first)
//    }
//    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//        tableView.scrollRectToVisible(rect!, animated: true)
//    }
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = getCurrentFormModel(indexPath)
     
//            print(model.name)
//            print(model.height)
   
        return  model.height
    }
    func getCurrentFormModel(_ indexPath : IndexPath) -> JSFormModel {
        var model:JSFormModel = JSFormModel();
        if (self.haveHeader) {
            let headerModel = self.datas[indexPath.section] as? JSFormHeaderModel
            model = headerModel!.content[indexPath.row] ;
        }else{
            model = self.datas[indexPath.row] as! JSFormModel;
        }
        return model;
    }
    
    func checkHaveEmptyField(block1 : (_ result:Bool,_ message : String)->Void){
        
        for field in self.datas {
            let field = field as? JSFormModel
            if field?.cellType == JSCellType.FXCellTypeMeida.rawValue {
                if field?.medias.count == 1 {
                    block1(true, "请上传"+field!.name)
                    return
                }
            }else
            {
                if (field?.text.count)!<=0 {
                    let prefix:String = (field?.cellType == JSCellType.FXCellTypeArrow.rawValue || field?.cellType == JSCellType.FXCellTypeCheckBox.rawValue) ? "请选择" : "请输入"
                    block1(true, prefix+field!.name)
                    return
                }else
                {
                    self.uploadDict.setValue(field?.text, forKey: (field?.key)!)
                }
            }

        }
        block1(false,"")
    }
        //可被编辑
        func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            if indexPath.section == 2 {
                return true
            }
            return false
        }
        //确定编辑模式（默认是滑动删除模式）
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
        //具体编辑操作（默认删除操作）
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
        let headerModel = self.datas[indexPath.section] as? JSFormHeaderModel
        headerModel?.content.remove(at: indexPath.row)
        goods.remove(at: indexPath.row)
        
        tableView.deleteRows(at: [indexPath], with: .top)
    }
    //    //允许移动某一行
    //    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    //        return true
    //    }
    //
    //    //实现排序
    //    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    //        //后面加as。。。
    //        let object:AnyObject = self.dataArray[sourceIndexPath.row] as AnyObject
    //        //
    //        self.dataArray.removeObject(at: sourceIndexPath.row)
    //        self.dataArray.insert(object, at: destinationIndexPath.row)
    //
    //
    //    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}
